package cn.yuanqiao.archive.jiashicang.service.impl;

import cn.yuanqiao.archive.appManager.mapper.InitArchiveMapper;
import cn.yuanqiao.archive.chengguojieshou.mapper.YqdaarticulatedMapper;
import cn.yuanqiao.archive.jiashicang.annotation.AroundAnnotation;
import cn.yuanqiao.archive.jiashicang.service.CockPitService;
import cn.yuanqiao.archive.task.util.HttpClientUtil;
import cn.yuanqiao.common.constant.CacheConstants;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.enums.DbIdEnum;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.service.RedisService;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.sql.YqDatabaseSQLUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class CockPitServiceImpl implements CockPitService {
    @Autowired
    private YqdaarticulatedMapper yqdaarticulatedMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private InitArchiveMapper initArchiveMapper;
    @Resource
    private SqlSessionFactory sqlSessionFactory;

    private static final Logger logger = LoggerFactory.getLogger(CockPitServiceImpl.class);

    /**
     *
     * @param map3
     * @param list
     * @param isManager 0=全部 1=租户(不包含管理单位) 2=管理单位
     */
    public void getTenantInfo(Map<String, Object> map3,List<String> list,Integer isManager){
        String manager = "";
        if(isManager == 1){
            manager = " and IS_MANAGER_DEPT = 'false' ";
        }else if(isManager == 2){
            manager = " and IS_MANAGER_DEPT = 'true' ";
        }
        String tenant = yqdaarticulatedMapper.getSingle("select " + YqDatabaseSQLUtil.YQ_WM_CONCAT("TENANTCODE||'-'||registered_unit") + " from manage_tenant where state = 0 "+manager);
        String[] split = tenant.split(",");
        for(int i=0;i<split.length;i++){
            String s = split[i];
            String[] split1 = s.split("-");
            list.add(split1[0]);
            map3.put(split1[0],split1[1]);
        }
    }


    @Override
    //@AroundAnnotation
    public JSONObject onlineNums() {
        logger.info("==========驾驶舱统计在线人数开始==========");
        long start=new Date().getTime();

        Map<String, Object> map3 = new HashMap<>();
        List<String> list = new ArrayList<>();
        getTenantInfo(map3,list,0);

        Map<String, Object> map = new HashMap<>();
        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        int totalNum = 0;
        //统计各个租户的在线人数
        for (String key : keys)
        {
            LoginUser user = redisService.getCacheObject(key);
            String tenantCode = user.getSysUser().getTenantCode();
            if (tenantCode!=null){
                Integer num = (Integer) map.putIfAbsent(tenantCode, 1);
                if(null!=num){
                    map.put(tenantCode,num+1);
                }
            }
        }
        //没有用户的赋值0
        for(String te:list){
            map.putIfAbsent(te, 0);
        }
        //统计总数替换租户名
        List<Map<String, Object>> objects = new ArrayList<>();
        Set<Map.Entry<String, Object>> entries = map.entrySet();
        Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
        while (iterator.hasNext()){
            Map.Entry<String, Object> next = iterator.next();
            String key = next.getKey();
            Integer value = (Integer)next.getValue();
            if(map3.containsKey(key)){
                Map<String, Object> objectHashMap = new HashMap<>();
                objectHashMap.put("tenantCode",key);
                objectHashMap.put("tenantName",map3.get(key));
                objectHashMap.put("num",value);
                objects.add(objectHashMap);
                totalNum+=value;
            }
        }
        /*Map<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("total",totalNum);
        objects.add(objectObjectHashMap);*/
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data",objects);
        jsonObject.put("time",DateUtils.getTime());
        long end=new Date().getTime();
        logger.info("==========驾驶舱统计在线人数结束==========");
        logger.info("驾驶舱统计在线人数耗时：：：{}毫秒",(end-start));
        return jsonObject;
    }

    @Override
    @AroundAnnotation
    public List<Map<String, Object>>  stockNums() {
        logger.info("==========驾驶舱库存统计开始==========");
        long start=new Date().getTime();

        Map<String, Object> map3 = new HashMap<>();
        List<String> list = new ArrayList<>();
        getTenantInfo(map3,list,0);

        String databaseId = sqlSessionFactory.getConfiguration().getDatabaseId();
        List<Map<String, Object>> objects = new ArrayList<>();
        for(String te:list){
            if(databaseId.equalsIgnoreCase(DbIdEnum.HIGHGO.getCode()) || databaseId.equalsIgnoreCase(DbIdEnum.KINGBASE.getCode())){
                te = te.toUpperCase();
            }
            Map<String, Object> map = new HashMap<>();
            int existTable = initArchiveMapper.isExistTable(te + "_YQDA");
            map.put("tenantCode",te);
            map.put("tenantName",map3.get(te));
            if(existTable!=0){
                String jianNum = yqdaarticulatedMapper.getSingle("select count(1) from " + te + "_YQDA where is_del=0 and state=5");
                String juanNum = yqdaarticulatedMapper.getSingle("select count(1) from " + te + "_YQFOLDER where is_del=0 and state=5");
                map.put("jianNum",Integer.valueOf(jianNum));
                map.put("juanNum",Integer.valueOf(juanNum));
            }else{
                map.put("jianNum",0);
                map.put("juanNum",0);
            }
            objects.add(map);
        }
        long end=new Date().getTime();
        logger.info("==========驾驶舱库存统计结束==========");
        logger.info("驾驶舱库存统计耗时：：：{}毫秒",(end-start));
        return objects;
    }

    @Override
    @AroundAnnotation
    public List<Map<String, Object>> storeRoomNums() {
        logger.info("==========驾驶舱库房统计开始==========");
        long start=new Date().getTime();

        Map<String, Object> map3 = new HashMap<>();
        List<String> list = new ArrayList<>();
        getTenantInfo(map3,list,0);

        String databaseId = sqlSessionFactory.getConfiguration().getDatabaseId();
        List<Map<String, Object>> objects = new ArrayList<>();
        for(String te:list){
            if(databaseId.equalsIgnoreCase(DbIdEnum.HIGHGO.getCode()) || databaseId.equalsIgnoreCase(DbIdEnum.KINGBASE.getCode())){
                te = te.toUpperCase();
            }
            Map<String, Object> map = new HashMap<>();
            int existTable = initArchiveMapper.isExistTable(te + "_CATEGORY");
            map.put("tenantCode",te);
            map.put("tenantName",map3.get(te));
            if(existTable!=0){
                String num = yqdaarticulatedMapper.getSingle("select sum(putaway_num) from " + te + "_YQGRID");
                map.put("num",StringUtils.isNull(num)?0:Integer.valueOf(num));
            }else{
                map.put("num",0);
            }
            objects.add(map);
        }

        long end=new Date().getTime();
        logger.info("==========驾驶舱库房统计结束==========");
        logger.info("驾驶舱库房统计耗时：：：{}毫秒",(end-start));
        return objects;
    }

    @Override
    @AroundAnnotation(type = "utilizing")
    public JSONObject utilizingStatisticsNums(String type) {
        logger.info("==========驾驶舱利用统计开始==========");
        long start=new Date().getTime();

        Map<String, Object> map3 = new HashMap<>();
        List<String> list = new ArrayList<>();
        getTenantInfo(map3,list,0);


        List<Map<String, Object>> objects = new ArrayList<>();
        List<Map<String, Object>> list1 = new ArrayList<>();
        Map<String, Object> map1 = new TreeMap<>();
        String fTime = "";
        if("day".equals(type)){     //按日  最近七日
            LocalDate today = LocalDate.now(); // 获取当前日期
            map1 = new TreeMap<>();
            String finalDay = "";
            for(int i=0;i<7;i++){
                String time = today.minusDays(i).toString();
                Map<String, Object> map2 = new HashMap<>();
                for(String te:list){
                    map2.put(te,0);
                }
                map1.put(time,map2);
                if(i==6){
                    finalDay = time;
                    fTime = time;
                }
            }
            list1 = yqdaarticulatedMapper.executeSql("select NAME,tenantcode,num from (" +
                    "select to_char(a.create_time,'yyyy-MM-dd') as NAME,a.tenantcode,count(a.borrow_id) as num from yqdaborrow a where a.create_time >= '"+finalDay+" 00:00:00'" +
                    " group by to_char(a.create_time,'yyyy-MM-dd'),a.tenantcode" +
                    ")");

        }
        if("month".equals(type)){   //按月 最近六个月
            DateTimeFormatter monthYearFormatter = DateTimeFormatter.ofPattern("yyyy-MM");
            YearMonth thisMonth = YearMonth.now();
            map1 = new TreeMap<>();
            String finalMonth = "";
            for(int i=0;i<6;i++){
                YearMonth thisMonth2 = thisMonth.minusMonths(i);
                String format = thisMonth2.format(monthYearFormatter);
                Map<String, Object> map2 = new HashMap<>();
                for(String te:list){
                    map2.put(te,0);
                }
                map1.put(format,map2);
                if(i==5){
                    finalMonth = format;
                    fTime = format;
                }
            }
            list1 = yqdaarticulatedMapper.executeSql("select NAME,tenantcode,num from (" +
                    "select to_char(a.create_time,'yyyy-MM') as NAME,a.tenantcode,count(a.borrow_id) as num from yqdaborrow a where a.create_time >= '" + finalMonth + "-01 00:00:00'" +
                    " group by to_char(a.create_time,'yyyy-MM'),a.tenantcode" +
                    ")");

        }

        for(int j=0;j<list1.size();j++){
            Map<String, Object> map = list1.get(j);
            String name = String.valueOf(map.get("NAME"));
            String tenantCode = String.valueOf(map.get("TENANTCODE"));
            if(StringUtils.isNotEmpty(tenantCode) && !"null".equals(tenantCode)){
                Integer num = Integer.valueOf(String.valueOf(map.get("NUM")));
                Map<String, Object> m = (Map<String, Object>)map1.get(name);
                Integer n = Integer.valueOf(String.valueOf(m.get(tenantCode)));
                m.put(tenantCode,n+num);
            }
        }

        //查询阅览室利用统计
        String bjfbonlineurl =  yqdaarticulatedMapper.getSingle("select config_value from sys_config where config_key = 'BJFBONLINEURL'");
        if(StringUtils.isEmpty(bjfbonlineurl) || "null".equals(bjfbonlineurl)){
            throw new ServiceException("BJFBONLINEURL未配置");
        }
        bjfbonlineurl = bjfbonlineurl.substring(0,bjfbonlineurl.indexOf("=")+1)+"utilizingStatisticsNums";

        Map<String, String> objectHashMap = new HashMap<>();
        objectHashMap.put("type",type);
        objectHashMap.put("time",fTime);
        String res = HttpClientUtil.doPost(bjfbonlineurl, objectHashMap);
        JSONObject jsonObject = JSONObject.parseObject(res);
        String code = jsonObject.getString("code");
        if(!"0".equals(code)){
            logger.error("查询阅览室利用统计失败");
        }
        JSONObject data = jsonObject.getJSONObject("data");

        //利用平台统计
        String lypturl =  yqdaarticulatedMapper.getSingle("select config_value from sys_config where config_key = 'LYPTURL'");
        if(StringUtils.isEmpty(lypturl) || "null".equals(lypturl)){
            throw new ServiceException("LYPTURL");
        }
        String res2 = HttpClientUtil.doPost(lypturl+"/LytjInterface/lytj", objectHashMap);
        JSONObject jsonObject2 = JSONObject.parseObject(res2);
        String code2 = jsonObject2.getString("code");
        if(!"0".equals(code2)){
            logger.error("查询利用平台利用统计失败");
        }
        JSONObject data2 = jsonObject2.getJSONObject("data");

        String managerDept = yqdaarticulatedMapper.getSingle("select tenantcode from manage_tenant where state = 0 and IS_MANAGER_DEPT = 'true'");

        int total = 0;
        int dzylsTotal = 0;
        int lyptTotal = 0;
        Set<Map.Entry<String, Object>> entries = map1.entrySet();
        Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
        while (iterator.hasNext()){
            Map.Entry<String, Object> next = iterator.next();
            Map<String, Object> map4 = new HashMap<>();
            String key = next.getKey();
            Map<String, Object> m = (Map<String, Object>)next.getValue();
            Set<Map.Entry<String, Object>> entries1 = m.entrySet();
            Iterator<Map.Entry<String, Object>> iterator1 = entries1.iterator();
            List<Map<String, Object>> list2 = new ArrayList<>();
            while (iterator1.hasNext()){
                Map.Entry<String, Object> next1 = iterator1.next();
                Map<String, Object> map5 = new HashMap<>();
                String key1 = next1.getKey();
                Integer value = Integer.valueOf(String.valueOf(next1.getValue()));
                map5.put("tenantCode",key1);
                map5.put("tenantName",map3.get(key1));
                map5.put("zhxtNum",value);
                if(key1.equals(managerDept)){   //只有管理单位有阅览室统计
                    boolean b = data.containsKey(key);
                    if(b){
                        Integer integer = data.getInteger(key);
                        dzylsTotal+=integer;
                        map5.put("dzylsNum",integer);
                    }else{
                        map5.put("dzylsNum",0);
                    }
                    boolean b1 = data2.containsKey(key);
                    if(b1){
                        Integer integer = data2.getInteger(key);
                        lyptTotal+=integer;
                        map5.put("lyptNum",integer);
                    }else{
                        map5.put("lyptNum",0);
                    }
                }else{
                    map5.put("lyptNum",0);
                    map5.put("dzylsNum",0);
                }
                total+=value;
                list2.add(map5);
            }
            map4.put(key,list2);
            objects.add(map4);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("zhxtTotal",total);
        map.put("dzylsTotal",dzylsTotal);
        map.put("lyptTotal",lyptTotal);
        objects.add(map);
        /*Map<String, Object> finalMap = new HashMap<>();
        finalMap.put("data",objects);
        finalMap.put("total",map);*/

        Map<String, Object> zhxtMap = new HashMap<>();
        Map<String, Object> dzylsMap = new HashMap<>();
        Map<String, Object> lyptMap = new HashMap<>();
        List<String> tenantName = new ArrayList<>();
        for(int k=0;k<objects.size()-1;k++){
            Map<String, Object> map2 = objects.get(k);
            Set<Map.Entry<String, Object>> entries1 = map2.entrySet();
            Iterator<Map.Entry<String, Object>> iterator1 = entries1.iterator();
            while (iterator1.hasNext()){
                Map.Entry<String, Object> next = iterator1.next();
                String key = next.getKey();  //日期
                List<Map<String, Object>> value = (List<Map<String, Object>>)next.getValue();
                List<Integer> list2 = new ArrayList<>();
                List<Integer> list3 = new ArrayList<>();
                List<Integer> list4 = new ArrayList<>();
                for(int i=0;i<value.size();i++){
                    Map<String, Object> map4 = value.get(i);
                    list2.add(Integer.valueOf(map4.get("zhxtNum").toString()));
                    list3.add(Integer.valueOf(map4.get("dzylsNum").toString()));
                    list4.add(Integer.valueOf(map4.get("lyptNum").toString()));
                    if(k==0){
                        tenantName.add(map4.get("tenantName").toString());
                    }
                }
                zhxtMap.put(key,list2);
                dzylsMap.put(key,list3);
                lyptMap.put(key,list4);
            }
        }
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("zhxtData",zhxtMap);
        jsonObject1.put("dzylsData",dzylsMap);
        jsonObject1.put("lyptData",lyptMap);
        jsonObject1.put("tenantName",tenantName);

        long end=new Date().getTime();
        logger.info("==========驾驶舱利用统计结束==========");
        logger.info("驾驶舱利用统计耗时：：：{}毫秒",(end-start));
        return jsonObject1;
    }

    @Override
    @AroundAnnotation
    public List<Map<String, Object>> archiveFileNums() {
        logger.info("==========驾驶舱电子档案归档统计饼状图开始==========");
        long start=new Date().getTime();

        Map<String, Object> map3 = new HashMap<>();
        List<String> list = new ArrayList<>();
        getTenantInfo(map3,list,0);

        //List<Integer> yearList = DateUtils.getLastSixYears();
        List<Map<String,Object>> arrayList = new ArrayList<>();
        String databaseId = sqlSessionFactory.getConfiguration().getDatabaseId();
        int total = 0;
        Map<String, Object> map = new HashMap<>();
        for(String tenant:list){
            if(databaseId.equalsIgnoreCase(DbIdEnum.HIGHGO.getCode()) || databaseId.equalsIgnoreCase(DbIdEnum.KINGBASE.getCode())){
                tenant = tenant.toUpperCase();
            }
            int existTable = initArchiveMapper.isExistTable(tenant + "_CATEGORY");
            if(existTable!=0){
                String num = yqdaarticulatedMapper.getSingle("select count(1) from " + tenant + "_YQDA where is_del=0 and is_other_system=1");
                //String num = yqdaarticulatedMapper.getSingle("select count(1) from " + tenant + "_YQDA where is_del=0");
                Integer integer = Integer.valueOf(num);
                map.put(tenant,Integer.valueOf(integer));
                total+=integer;
            }else{
                map.put(tenant,0);
            }
        }

        for(String tenant1:list){
            Map<String, Object> map2 = new HashMap<>();
            String num2 = String.valueOf(map.get(tenant1));
            map2.put("tenantCode",tenant1);
            map2.put("tenantName",map3.get(tenant1));
            if(total!=0){
                BigDecimal result = new BigDecimal(num2)
                        .divide(new BigDecimal(total), 3, RoundingMode.HALF_UP);
                // 转换为百分比
                BigDecimal percentageResult = result.multiply(new BigDecimal(100)).setScale(3, RoundingMode.HALF_UP);
                String num = percentageResult.toString();
                map2.put("num1",num2);
                map2.put("num2",num.substring(0,num.length()-1));
                arrayList.add(map2);
            }else{
                map2.put("num1",num2);
                map2.put("num2","0.00");
                arrayList.add(map2);
            }
        }

        long end=new Date().getTime();
        logger.info("==========驾驶舱电子档案归档统计饼状图结束==========");
        logger.info("驾驶舱电子档案归档统计饼状图耗时：：：{}毫秒",(end-start));
        return arrayList;
    }

    @Override
    @AroundAnnotation
    public JSONObject archiveFileNums2() {
        logger.info("==========驾驶舱电子档案归档统计折线图开始==========");
        long start=new Date().getTime();

        Map<String, Object> map3 = new HashMap<>();
        List<String> list = new ArrayList<>();
        getTenantInfo(map3,list,0);
        List<Map<String, Object>> objects = new ArrayList<>();
        List<Integer> yearList = DateUtils.getLastSixYears();
        Map<String, Object> map = new TreeMap<>();
        String finalYear = "";
        Map<String,Integer> locationMap = new HashMap<>();
        for(int i = 0;i<yearList.size();i++){
            Integer integer = yearList.get(i);
            /*Map<String, Object> map2 = new HashMap<>();
            for(String te:list){
                map2.put(te,0);
            }
            map.put(integer.toString(),map2);*/
            if(i==0){
                finalYear = integer.toString();
            }
            locationMap.put(integer.toString(),i);
        }
        for(String tenant:list){
            List<Integer> list1 = new ArrayList<>();
            for(int i=0;i<yearList.size();i++){
                list1.add(0);
            }
            map.put(tenant,list1);
        }


        String databaseId = sqlSessionFactory.getConfiguration().getDatabaseId();
        for(String tenant:list){
            String te = tenant;
            if(databaseId.equalsIgnoreCase(DbIdEnum.HIGHGO.getCode()) || databaseId.equalsIgnoreCase(DbIdEnum.KINGBASE.getCode())){
                tenant = tenant.toUpperCase();
            }
            int existTable = initArchiveMapper.isExistTable(tenant + "_CATEGORY");
            if(existTable!=0){
                List<Map<String, Object>> list1 = yqdaarticulatedMapper.executeSql("select NAME,num from (" +
                        "select to_char(a.create_time,'yyyy') as NAME,count(a.da_id) as num from " + te + "_YQDA a where a.is_other_system=1 and a.is_del=0 and a.create_time >= '" + finalYear + "-01-01 00:00:00'" +
                        //"select to_char(a.create_time,'yyyy') as NAME,count(a.da_id) as num from " + tenant + "_YQDA a where a.is_del=0 and a.create_time >= '" + finalYear + "-01-01 00:00:00'" +
                        " group by to_char(a.create_time,'yyyy'))");
                for(int j=0;j<list1.size();j++){
                    Map<String, Object> map1 = list1.get(j);
                    String name = String.valueOf(map1.get("NAME"));  //年度
                    String num = String.valueOf(map1.get("NUM"));   //数量
                    Integer local = locationMap.get(name);
                    List<Integer> integerList = (List<Integer>)map.get(te);
                    integerList.set(local,Integer.valueOf(num));
                    //Map<String, Object> map2 = (Map<String, Object>)map.get(name);
                    //Integer num2 = Integer.valueOf(String.valueOf(map2.get(tenant)));
                    //map2.put(tenant,num2+Integer.valueOf(num));
                }
            }
        }

        JSONObject jsonObject = new JSONObject();
        Set<Map.Entry<String, Object>> entries = map.entrySet();
        Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
        JSONArray jsonArray = new JSONArray();
        while (iterator.hasNext()){
            Map.Entry<String, Object> next = iterator.next();
            String key = next.getKey();
            List<Integer> integerList = (List<Integer>)next.getValue();
            JSONArray jsonArray1 = new JSONArray();
            jsonArray1.add(map3.get(key));
            for(int i=0;i<integerList.size();i++){
                jsonArray1.add(integerList.get(i));
            }
            jsonArray.add(jsonArray1);
        }
        jsonObject.put("data",jsonArray);
        jsonObject.put("time",yearList);

        long end=new Date().getTime();
        logger.info("==========驾驶舱电子档案归档统计折线图结束==========");
        logger.info("驾驶舱电子档案归档统计折线图耗时：：：{}毫秒",(end-start));
        return jsonObject;
    }

    @Override
    @AroundAnnotation
    public List<Map<String, Object>> digitalStatisticsNums() {
        logger.info("==========驾驶舱数字化统计开始==========");
        long start=new Date().getTime();

        Map<String, Object> map3 = new HashMap<>();
        List<String> list = new ArrayList<>();
        getTenantInfo(map3,list,0);

        String databaseId = sqlSessionFactory.getConfiguration().getDatabaseId();
        List<Map<String, Object>> objects = new ArrayList<>();
        for(String tenant:list){
            if(databaseId.equalsIgnoreCase(DbIdEnum.HIGHGO.getCode()) || databaseId.equalsIgnoreCase(DbIdEnum.KINGBASE.getCode())){
                tenant = tenant.toUpperCase();
            }
            Map<String, Object> map = new HashMap<>();
            int existTable = initArchiveMapper.isExistTable(tenant + "_CATEGORY");
            map.put("tenantCode",tenant);
            map.put("tenantName",map3.get(tenant));
            if(existTable!=0){
                String totalNum = yqdaarticulatedMapper.getSingle("select count(1) from " + tenant + "_YQDA where js_type=2 and is_del=0");
                String count1 = yqdaarticulatedMapper.getSingle("select count(1) from " + tenant + "_YQDA where js_type=2 and is_del=0 and EFILE_COUNT=0");
                if("0".equals(totalNum)){
                    map.put("wszhNum","0");
                    map.put("szhNum","0");
                    objects.add(map);
                    continue;
                }
                BigDecimal result = new BigDecimal(count1)
                        .divide(new BigDecimal(totalNum), 3, RoundingMode.HALF_UP);
                // 转换为百分比
                BigDecimal percentageResult = result.multiply(new BigDecimal(100)).setScale(3, RoundingMode.HALF_UP);
                String num = percentageResult.toString();
                map.put("wszhNum",num.substring(0,num.length()-2));


                BigDecimal result2 = new BigDecimal(Long.valueOf(totalNum)-Long.valueOf(count1))
                        .divide(new BigDecimal(totalNum), 3, RoundingMode.HALF_UP);
                // 转换为百分比
                BigDecimal percentageResult2 = result2.multiply(new BigDecimal(100)).setScale(3, RoundingMode.HALF_UP);
                String num2 = percentageResult2.toString();
                map.put("szhNum",num2.substring(0,num2.length()-2));
            }else{
                map.put("wszhNum","0");
                map.put("szhNum","0");
            }
            objects.add(map);
        }


        long end=new Date().getTime();
        logger.info("==========驾驶舱数字化统计结束==========");
        logger.info("驾驶舱数字化统计耗时：：：{}毫秒",(end-start));
        return objects;
    }

    @Override
    @AroundAnnotation
    public JSONObject handOverReceiveNums() {
        logger.info("==========驾驶舱移交统计开始==========");
        long start=new Date().getTime();
        List<Map<String, Object>> listData = new ArrayList<>();
        //获取所有租户信息
        Map<String, Object> map3 = new HashMap<>();
        List<String> list = new ArrayList<>();
        getTenantInfo(map3,list,1);
        //获取每个租户移交数
        int zongYj = 0;
        for (String tenantCode:list){
            int existTable = initArchiveMapper.isExistTable(tenantCode + "_HAND_OVER_RECEIVE");
            if(existTable!=0){
                String sql = "select COUNT(1) from "+tenantCode+"_HAND_OVER_RECEIVE a inner join "+tenantCode+"_HAND_OVER_DA b on b.HAND_OVER_ID = a.ID where a.STATE = 2 and b.DA_TYPE = 0";
                String num = yqdaarticulatedMapper.getSingle(sql);
                zongYj+=Integer.valueOf(num);
                Map<String,Object> data = new HashMap<>();
                data.put("name", String.valueOf(map3.get(tenantCode)));
                data.put("val", num);
                listData.add(data);
            }
        }
        JSONObject object = new JSONObject();
        object.put("zong",zongYj);
        object.put("data",listData);
        long end=new Date().getTime();
        logger.info("==========驾驶舱移交统计结束==========");
        logger.info("驾驶舱移交统计耗时：：：{}毫秒",(end-start));
        return object;
    }

    @Override
    @AroundAnnotation
    public JSONObject receptionNums() {
        logger.info("==========驾驶舱接收统计开始==========");
        long start=new Date().getTime();
        List<Map<String, Object>> listData = new ArrayList<>();
        //获取所有租户信息
        Map<String, Object> map3 = new HashMap<>();
        List<String> list = new ArrayList<>();
        getTenantInfo(map3,list,1);
        //获取每个租户接收数
        int zongYj = 0;
        //查询管理单位
        List<String> manager = new ArrayList<>();
        getTenantInfo(new HashMap<>(),manager,2);
        String tenantCodeManager = manager.get(0);
        for (String tenantCode:list){
            int existTable = initArchiveMapper.isExistTable(tenantCodeManager + "_ONLINE_PACKAGE_DA");
            if(existTable!=0){
                String sql = "select COUNT(1) from YQDA_ONLINE_RECEPTION a inner join "+tenantCodeManager+"_ONLINE_PACKAGE_DA b on b.ONLINE_RECEPTION_ID = a.ID where a.STATE = 2 and b.DA_TYPE = 0 and a.OLD_TENANTCODE = '"+tenantCode+"'";
                String num = yqdaarticulatedMapper.getSingle(sql);
                zongYj+=Integer.valueOf(num);
                Map<String,Object> data = new HashMap<>();
                data.put("name", String.valueOf(map3.get(tenantCode)));
                data.put("val", num);
                listData.add(data);
            }
        }
        JSONObject object = new JSONObject();
        object.put("zong",zongYj);
        object.put("data",listData);
        long end=new Date().getTime();
        logger.info("==========驾驶舱接收统计结束==========");
        logger.info("驾驶舱接收统计耗时：：：{}毫秒",(end-start));
        return object;
    }

    @Override
    @AroundAnnotation
    public JSONArray handOverReceiveNumsByYear() {
        logger.info("==========驾驶舱移交统计按年度开始==========");
        long start=new Date().getTime();
        JSONArray listData = new JSONArray();
        //获取所有租户信息
        Map<String, Object> map3 = new HashMap<>();
        List<String> list = new ArrayList<>();
        getTenantInfo(map3,list,1);

        List<Integer> yearList = DateUtils.getLastTenYears();
        Map<Integer,Integer> mapData = new HashMap<>();
        for(Integer year:yearList){
            mapData.put(year,0);
        }

        for (String tenantCode:list){
            int existTable = initArchiveMapper.isExistTable(tenantCode + "_HAND_OVER_RECEIVE");
            if(existTable!=0){
                String sql = "select to_char(a.create_time,'YYYY') as year,COUNT(1) as num from "+tenantCode+"_HAND_OVER_RECEIVE a inner join "+tenantCode+"_HAND_OVER_DA b on b.HAND_OVER_ID = a.ID where a.STATE = 2 and b.DA_TYPE = 0 group by to_char(a.create_time,'YYYY')";
                List<Map<String,Object>> num = yqdaarticulatedMapper.executeSql(sql);
                for(Integer year:yearList){
                    for(Map<String,Object> data:num){
                        if(data.get("YEAR").equals(String.valueOf(year))){
                            mapData.put(year,(mapData.get(year)+Integer.valueOf(data.get("NUM").toString())));
                        }
                    }
                }
            }
        }

        for(int i = yearList.size()-1;i>=0;i--){
            JSONObject object = new JSONObject();
            object.put("name",yearList.get(i));
            object.put("num",mapData.get(yearList.get(i)));
            listData.add(object);
        }

        /*for(Integer year:yearList){
            JSONObject object = new JSONObject();
            object.put("name",year);
            object.put("num",mapData.get(year));
            listData.add(object);
        }*/

        long end=new Date().getTime();
        logger.info("==========驾驶舱移交统计按年度结束==========");
        logger.info("驾驶舱移交统计耗时：：：{}毫秒",(end-start));
        return listData;
    }

    @Override
    @AroundAnnotation
    public JSONArray receptionNumsByYear() {
        logger.info("==========驾驶舱接收统计按年度开始==========");
        long start=new Date().getTime();
        JSONArray listData = new JSONArray();
        //获取所有租户信息
        Map<String, Object> map3 = new HashMap<>();
        List<String> list = new ArrayList<>();
        getTenantInfo(map3,list,1);

        List<Integer> yearList = DateUtils.getLastTenYears();
        Map<Integer,Integer> mapData = new HashMap<>();
        for(Integer year:yearList){
            mapData.put(year,0);
        }
        //查询管理单位
        List<String> manager = new ArrayList<>();
        getTenantInfo(new HashMap<>(),manager,2);
        String tenantCodeManager = manager.get(0);
        for (String tenantCode:list){
            int existTable = initArchiveMapper.isExistTable(tenantCodeManager + "_ONLINE_PACKAGE_DA");
            if(existTable!=0){
                String sql = "select to_char(a.create_time,'YYYY') as year,COUNT(1) as num from YQDA_ONLINE_RECEPTION a inner join "+tenantCodeManager+"_ONLINE_PACKAGE_DA b on b.ONLINE_RECEPTION_ID = a.ID where a.STATE = 2 and b.DA_TYPE = 0 and a.OLD_TENANTCODE = '"+tenantCode+"' group by to_char(a.create_time,'YYYY')";
                List<Map<String,Object>> num = yqdaarticulatedMapper.executeSql(sql);
                for(Integer year:yearList){
                    for(Map<String,Object> data:num){
                        if(data.get("YEAR").equals(String.valueOf(year))){
                            mapData.put(year,(mapData.get(year)+Integer.valueOf(data.get("NUM").toString())));
                        }
                    }
                }
            }
        }

        for(int i = yearList.size()-1;i>=0;i--){
            JSONObject object = new JSONObject();
            object.put("name",yearList.get(i));
            object.put("num",mapData.get(yearList.get(i)));
            listData.add(object);
        }

        long end=new Date().getTime();
        logger.info("==========驾驶舱接收统计按年度结束==========");
        logger.info("驾驶舱接收统计耗时：：：{}毫秒",(end-start));
        return listData;
    }

    @Override
    public int updateRedisData() {
        logger.info("==========驾驶舱更新redis缓存开始==========");
        long start=new Date().getTime();
        List<Map<String, Object>> list = stockNums();
        redisService.setCacheObject("cockPit:stockNums",list);
        List<Map<String, Object>> list1 = storeRoomNums();
        redisService.setCacheObject("cockPit:storeRoomNums",list1);
        JSONObject day = utilizingStatisticsNums("day");
        redisService.setCacheObject("cockPit:utilizingStatisticsNums:day",day);
        JSONObject month = utilizingStatisticsNums("month");
        redisService.setCacheObject("cockPit:utilizingStatisticsNums:month",month);
        List<Map<String, Object>> list2 = archiveFileNums();
        redisService.setCacheObject("cockPit:archiveFileNums",list2);
        JSONObject jsonObject2 = archiveFileNums2();
        redisService.setCacheObject("cockPit:archiveFileNums2",jsonObject2);
        List<Map<String, Object>> list4 = digitalStatisticsNums();
        redisService.setCacheObject("cockPit:digitalStatisticsNums",list4);
        JSONObject jsonObject = handOverReceiveNums();
        redisService.setCacheObject("cockPit:handOverReceiveNums",jsonObject);
        JSONObject jsonObject1 = receptionNums();
        redisService.setCacheObject("cockPit:receptionNums",jsonObject1);
        JSONArray objects = handOverReceiveNumsByYear();
        redisService.setCacheObject("cockPit:handOverReceiveNumsByYear",objects);
        JSONArray objects1 = receptionNumsByYear();
        redisService.setCacheObject("cockPit:receptionNumsByYear",objects1);
        long end=new Date().getTime();
        logger.info("==========驾驶舱更新redis结束==========");
        logger.info("驾驶舱更新redis耗时：：：{}毫秒",(end-start));
        return 1;
    }

}
